import { defineStore } from "pinia";
import { ref } from "vue";
import { userGetInfoService } from "@/api";
import { asyncRoutes } from "@/router";
import router from "@/router";

const useUserStore = defineStore(
  "mian-user",
  () => {
    const token = ref("");
    let user = ref({});
    let groupRoutes = ref({});
    let filteredRoutesToAdd = ref([]);

    const setToken = (t) => {
      token.value = t;
    };

    const getUserInfo = async () => {
      const res = await userGetInfoService();
      user.value = res.data;
      // await handleFilteredRoutes();
    };

    const setUserInfo = () => {
      user.value = {};
      groupRoutes.value = {};
      filteredRoutesToAdd.value = [];
    };

    const handleFilteredRoutes = async () => {
      const filteredRoutes = await filterRoutesByUserMenus(user.value.routers);
      filteredRoutesToAdd.value = filteredRoutes;
      await addAsyncRoutes(filteredRoutes);
      await handleGroupRoutes(filteredRoutes);
    };

    const filterRoutesByUserMenus = async (userMenus) => {
      // 初始化过滤后的路由数组
      const filteredRoutes = [];
      // 使用预处理的映射表加速查找
      const routesMap = asyncRoutes.reduce((map, route) => {
        map[route.name] = route;
        return map;
      }, {});

      // 遍历用户菜单，筛选出对应路由
      userMenus.forEach((menu) => {
        if (menu.children) {
          menu.children.forEach((child) => {
            // 查找与菜单匹配的路由
            const matchedRoute = routesMap[child.name];
            if (matchedRoute) {
              // 如果找到，添加到过滤后的路由数组
              filteredRoutes.push(matchedRoute);
            }
          });
        } else {
          const matchedRoute = routesMap[menu.name];
          if (matchedRoute) {
            filteredRoutes.push(matchedRoute); // 找到则添加
          }
        }
      });

      return filteredRoutes;
    };
    /* const filterRoutesByUserMenus = (userMenus) => {
      const filteredRoutes = [];
      userMenus.forEach((menu) => {
        if (menu.children) {
          menu.children.forEach((child) => {
            const matchedRoute = asyncRoutes.find(
              (route) => route.name === child.name
            );
            if (matchedRoute) {
              filteredRoutes.push(matchedRoute);
            }
          });
        } else {
          const matchedRoute = asyncRoutes.find(
            (route) => route.name === menu.name
          );
          if (matchedRoute) {
            filteredRoutes.push(matchedRoute);
          }
        }
      });
      return filteredRoutes;
    }; */

    /**
     * 根据出现次数对路由进行分组
     * @param {Array} filteredRoutes 过滤后的路由数组
     */
    const handleGroupRoutes = async (filteredRoutes) => {
      // 初始化数据和名称计数器
      let data = filteredRoutes;
      let nameCounts = {};
      // 计算各路由名称出现的次数
      data.forEach((item) => {
        let name = item.path.split("/")[1];
        nameCounts[name] = (nameCounts[name] || 0) + 1;
      });
      // 根据出现次数进行分组
      let filteredDataByCount = {};
      for (let item of data) {
        let name = item.path.split("/")[1];
        if (nameCounts[name] > 2) {
          if (nameCounts[name] >= 2) {
            if (!filteredDataByCount[name]) {
              filteredDataByCount[name] = [];
            }
            filteredDataByCount[name].push(item);
          }
        }
        // 处理出现一次的路由
        let uniqueData = data.filter((item) => {
          let name = item.path.split("/")[1];
          return nameCounts[name] === 1;
        });
        // 合并分组结果
        groupRoutes.value = { ...filteredDataByCount, uniqueData };
        // groupRoutes = groupRoutes; // 保存路由分组结果
      }
    };
    /**
     * 异步添加路由方法
     * @param {Array} filteredRoutes - 过滤后的路由数组，如果为null或undefined，则从localStorage获取要添加的路由
     * @returns {Promise<void>} 不返回任何内容
     */
    const addAsyncRoutes = async (filteredRoutes) => {
      // 当传入的过滤后路由为空时，从localStorage获取要添加的路由
      if (!filteredRoutes) {
        let { filteredRoutesToAdd } = JSON.parse(
          localStorage.getItem("mian-user")
        );
        // 为每个路由项动态设置组件
        filteredRoutesToAdd.forEach((item) => {
          item.component = () => import(`/src/views${item.path}.vue`);
        });
        filteredRoutes = filteredRoutesToAdd;
      }

      // 查找名称为"index"的路由，并更新其children属性，将新路由项添加至其后
      const indexRoute = router
        .getRoutes()
        .find((route) => route.name === "index");
      if (indexRoute) {
        indexRoute.children = [
          indexRoute.children[0],
          indexRoute.children[1],
          ...filteredRoutes,
        ];
      }
      // 将更新后的路由添加至路由表
      router.addRoute(indexRoute);

      /*
      vue-router4的最新方法，可以直接添加子路由
       filteredRoutesToAdd.forEach((item) => {
        router.addRoute("index", item);
      }); */

      // 打印更新后的路由表
      console.log(router.getRoutes());
    };

    return {
      token,
      setToken,
      getUserInfo,
      user,
      setUserInfo,
      handleFilteredRoutes,
      groupRoutes,
      filteredRoutesToAdd,
      addAsyncRoutes,
    };
  },
  {
    persist: true,
  }
);

export { useUserStore };
